package com.miao.im.support.disruptor;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.miao.im.support.pulisher.BaseEvent;
import com.miao.im.support.pulisher.IEventProducer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/3/18 11:31
 * @Description:
 */
@Component
public class DisruptorProducer implements IEventProducer {
    @Autowired
    private Disruptor<DisruptorEvent<?>> disruptor;

    @Override
    public void publish(BaseEvent event) {
        RingBuffer<DisruptorEvent<?>> ringBuffer = disruptor.getRingBuffer();
        long sequence = ringBuffer.next();
        try {
            if (event instanceof DisruptorEvent) {
                DisruptorEvent event1 = (DisruptorEvent) event;
                DisruptorEvent disruptorEvent = ringBuffer.get(sequence);
                disruptorEvent.setPayload(event1.getPayload());
                disruptorEvent.setEventType(event1.getEventType());
            }
        } finally {
            ringBuffer.publish(sequence);
        }
    }
}
